package com.yzf.demo.demo.Thread;

import java.util.concurrent.TimeUnit;

/**
 * Created by 于占峰 on 2020/3/31/031.
 * <p>
 * 如何终止线程示例
 */
public class StopDemo {
    //通过共享变量控制线程结束
    private static boolean stop = false;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new StopThread());
        t1.start();
        //t1.stop();属于操作计算底层强制终止
        //休眠两秒 然后设置sop为true
        TimeUnit.SECONDS.sleep(2);
        stop = true;
    }

    static class StopThread implements Runnable {

        @Override
        public void run() {
            while (!stop) {
                System.out.println("持续运行");
                try {
                    //睡眠一秒
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
